前幾天分別講解子查詢、集合運算的使用, 今日會更進階的搭配邏輯運算子進行資料的查詢。
常用的邏輯運算子
| 運算子 | Function | 
|---|---|
| AND | A且B (兩條件 皆成立 or 兩集合皆存在 | 
| OR | A或者B (兩條件 擇一成立 or 兩集合擇一存在) | 
| ESIXTS | 存在 (常用於主查詢是否含有子查詢的結果) | 
| IN | 用於值存在於集合 | 
| LIKE | 用於比對搜尋 (通常搭配 萬用字元or跳脫字元寫比對公式) | 
| NOT | 非 (可搭配 AND / EXISTS 使用) | 
Example使用的table
with Travel as (
    select 'Amy' name, 'Japan' country
    union all
    select 'Oleve' name, 'Denmark' country
    union all
    select 'Jake' name, 'France' country
    union all
    select 'Luisa' name, 'Greece' country
    union all
    select 'Freddy%' name, 'Japan' country
    union all
    select 'Freddy%' name, 'Greece' country  -- 新增一項
), Student as (
    select 'Amy' name, 123456 ID
    union all
    select 'Oleve' name, 567899 ID
    union all
    select 'Jake' name, 586966 ID
)
交集相同select name from Travel t
where 1=1
and exists (
  select t2.name from Student t2
  where t.name = t2.name
)
;
-- output
Amy
Oleve
Jake
差集邏輯相同, 但差別在於不移除重複項目select name from Travel t
where 1=1
and not exists (
  select t2.name from Student t2
  where t.name = t2.name
)
;
-- output
Luisa
Freddy%
Freddy%  -- 出現第二次
曾經被問過 in 跟 like 差別在哪裡, 因此分別舉例兩者用法, 希望能幫助讀者理解,
in 用於比對元素是否存在於子查詢結果中, 而like用於比對字串中是否存有特定字元
select name from Travel t
where 1=1
and name in (
  select t2.name from Student t2
)
;
-- output
Amy
Oleve
Jake
%代表任一字元, _代表一個字元, 若想比對%、_等保留字元,則須要搭配escape '\'做比對。select name from Travel t
where 1=1
and name like '%L%' --比對字串中是否符合字母L
;
-- output
Luisa
select name from Travel t
where 1=1
and upper(name) like '%L%'  --比對字串中是否符合`大小寫`字母L
;
-- output
Oleve
Luisa
select name from Travel t
where 1=1
and name like '__e%'  --比對字串中是否符合第三個字元是`e`
;
-- output
Oleve
Freddy%
Freddy%
select distinct name from Travel t
where 1=1
and name like '%\%%' escape '\'  --比對字串中是否符合存在字元是`%`
;
-- output
Freddy%